# Create your views here.
from django.conf import settings
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.template.context import Context
from django.template import RequestContext, loader
from django.forms.models import modelformset_factory
from django.contrib.auth.forms import *
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.views import *

from forms import CrearUsuarioForm

def new_password(request):
	return password_change(request, "registration/password_change_form.html")

def get_login_form(request):
	try:
		user_label = settings.LOGIN_USER_LABEL
	except:
		user_label = "Usuario"
	if request.method == "POST":
		if 'login' in request.POST:
			form = AuthenticationForm(data=request.POST)
			if form.is_valid():
				login(request, form.get_user())
				if request.session.test_cookie_worked():
					request.session.delete_test_cookie()
		else:
			form = AuthenticationForm()
			form.fields['username'].label = user_label
			return form
	else:
		form = AuthenticationForm()
	form.fields['username'].label = user_label
	return form
	
def login_short(request):
	login_form = get_login_form(request)
	if login_form.is_valid():
		if request.user.is_staff:
			return HttpResponseRedirect(settings.LOGIN_REDIRECT_ADMIN_URL)
		else:
			return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
	else:
		return render_to_response ('registration/login.html', locals(),context_instance=RequestContext(request))

def user_created(request):
	return render_to_response('user_created.html',locals(),context_instance=RequestContext(request))

def user_create(request):
	if request.method == 'POST':
		form = CrearUsuarioForm(request.POST, request.FILES)
		if form.is_valid():
			user = form.save()
			subject = "Le damos la bienvenida"
			c = {
				'username': user.username,
				'nombre': user.first_name,
				'apellido': user.last_name
			}
			send_mail_html(user.username, subject, 'email_bienvenido.html', c)
			return HttpResponseRedirect('/%s/accounts/user-created/' % settings.PROJECT_NAME)
		else:			
			return render_to_response('user_create.html',locals(),context_instance=RequestContext(request))
	else:
		form = CrearUsuarioForm()
		return render_to_response('user_create.html',locals(),context_instance=RequestContext(request))



